package net.pocrd.core.generator;

import net.pocrd.annotation.ConsoleArgument;
import net.pocrd.annotation.ConsoleJoinPoint;
import net.pocrd.annotation.ConsoleOption;
import net.pocrd.util.WebRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by rendong on 16/2/17.
 */
@ConsoleJoinPoint(command = "api-logger-gen", desc = "根据api文档生成每个接口的日志分析代码")
public class ApiLogParserGenerator {
    private static final Logger logger = LoggerFactory.getLogger(ApiLogParserGenerator.class);

    public static void generate(String website, String outputPath) {
        InputStream defaultXslt = null;
        try {
            defaultXslt = ApiSdkJavaGenerator.class.getResourceAsStream("/xslt/logparser.xslt");
            Transformer trans = TransformerFactory.newInstance().newTransformer(new StreamSource(defaultXslt));
            trans.setOutputProperty("omit-xml-declaration", "yes");
            byte[] bytes = WebRequestUtil.getResponseBytes(website, null);
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(bytes));
            trans.transform(new DOMSource(document), new StreamResult(outputPath + "/AutoGeneratedParser.java"));
        } catch (Exception e) {
            logger.error("generate failed!", e);
            throw new RuntimeException("generate failed!", e);
        } finally {
            try {
                if (defaultXslt != null) {
                    defaultXslt.close();
                }
            } catch (IOException e) {
                logger.error("close failed!", e);
                throw new RuntimeException("close failed!", e);
            }
        }
    }

    public static void execute(
            @ConsoleOption(name = "o", desc = "输出目录") String outputPath,
            @ConsoleArgument(name = "url", desc = "api文档地址", sample = "http://www.pocrd.net/info.api?raw") String url) {
        generate(url, outputPath == null ? "." : outputPath);
    }
}
